# @Time : 2021/4/8 17:57
# @Author : Fioman
# @Phone : 13149920693
import threading
from db_tools.db_handler import DbHandler
from tools.hd_logger import HdLogger
import settings
from tools.send_to_ui_tools import *
from AGV_msg.AGV_communicate import *
import gevent
import socket

"""
设备状态监控,每个设备创建一个线程,用来控制设备的状态,检测到设备状态以后要做的事情.
"""


class StatesListener(object):
    def __init__(self, mainZmc, camZmc, camera1, deviceStates, sqlHd):
        self.db = DbHandler()
        self.logger = HdLogger()
        self.states = deviceStates
        self.camera1 = camera1
        # self.sqlHd = sqlHd
        # self.camera2 = camera2
        self.mainZmc = mainZmc
        self.camZmc = camZmc
        self.loopDuration = 0.5

        self.states.client_socket = None
        # 创建一个TCP/IP套接字
        self.socketService = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 绑定服务器地址和端口
        self.logger = HdLogger()
        self.cameraGroupStates = False
        # self.server_address = ("192.168.0.3", 11258)
        self.click_address = ("192.168.0.12", 9000)
        # # 创建socket服务器
        # self.socketService.bind(self.server_address)
        # # 开始监听连接
        # self.socketService.listen(5)
        print('通讯服务正在运行，等待接收信息...')
        self.logger.debug("通讯服务正在运行，等待接收信息...")
        self.managerThread = threading.Thread(target=self.manager, name="managerThread")
        self.handlerThread = threading.Thread(target=self.Handler, name="handlerThread")
        self.mainZmcListenerThread = threading.Thread(target=self.main_zmc_listener, name="mainZmcListenerThread")
        self.camZmcListenerThread = threading.Thread(target=self.cam_zmc_listener, name="camZmcListenerThread")
        self.cameraGroupListenerThread = threading.Thread(target=self.camera_group_listener, name="cameraGroupListenerThread")
        self.AGVCommunicateListenerThread = threading.Thread(target=self.AGV_communicate_listener, name="AGVCommunicateListenerThread")
        self.infoStartAGV = ""
        self.AGVSendFileThreadStart = False
        self.QRCode = ""
        self.taskStatus = False
        self.timestamp = ""

    def main_zmc_listener(self):
        """
        收板控制器的监听线程类
        :return:
        """
        self.states.mainZmcIsRun = True
        while settings.IS_MAIN_ALIVE:
            try:
                connectState = self.mainZmc.check_connect()
                if connectState:
                    val = [self.mainZmc.get_modbus_bit(bitNum, 1)[1][0] for bitNum in range(500, 535)]
                    alarmInfo = self.get_main_alarm_info_by_bit_val(val)
                    self.states.mainAlarmInfo = alarmInfo
                    # 用来向上位机发送异常状态的
                    if alarmInfo != "" and not self.states.mainAlarmInfoVisible:
                        alarmInfoVal = [500 + index for index, bitVal in enumerate(val) if bitVal != 0]
                        # self.sqlHd.update_table_qp_data_alarm("急停报警异常", alarmInfoVal)
                    self.states.mainAlarmInfoVisible = True if alarmInfo != "" else False

                    grateHidded = self.mainZmc.get_grade_state()
                    self.states.grateHidded = grateHidded

                    doorAlarm = self.mainZmc.get_door_state()
                    self.states.doorAlarm = doorAlarm

                    pinFlag = self.mainZmc.get_pin_flag()
                    self.states.pinFlag = pinFlag

                    BMSR = self.mainZmc.get_modbus_bit(70, 1)[1][0]
                    self.states.BMSR = True if BMSR == 1 else False
                    if not self.states.BMSR and self.AGVSendFileThreadStart:
                        self.set_AGV_call_off_request()

                    # 获取已经存放的板的厚度,并且存放到数据库
                    thicknessFinished1, thicknessFinished2 = self.mainZmc.get_modbus_float(100, 2)[1]
                    query = {"key": "1"}
                    tableName = self.db.putBoardThicknessTable
                    newData = {
                        "thicknessFinished1": thicknessFinished1,
                        "thicknessFinished2": thicknessFinished2,
                    }
                    newValues = {
                        "$set": newData
                    }
                    self.db.update_data(tableName, query, newValues)

                    # 获取当前的作业去向
                    toWhere = self.mainZmc.get_to_where_state()
                    self.states.toWhere = toWhere

                    # 获取收料平台是否放满的状态信号
                    fullStateList = self.mainZmc.get_Lv_full_state()
                    self.states.fullStateLV01, self.states.fullStateLV02 = fullStateList

                    # 根据载料台状态显示界面按钮
                    self.states.changeLv1Button = True if self.mainZmc.get_modbus_bit(58, 1)[1][0] == 0 else False
                    self.states.changeLv2Button = True if self.mainZmc.get_modbus_bit(59, 1)[1][0] == 0 else False

                    self.states.infoStartAGV = self.infoStartAGV

                    ret, val = self.mainZmc.is_rs_stop()
                    if ret != 0:
                        if val == 1:
                            self.states.mainZmcStates.rs = True
                            if not self.states.mainZmcIsRs:
                                self.states.mainZmcIsRs = True
                                newData = {
                                    "mainZmcRunning": 2
                                }
                                self.db.save_working_info_data(newData)
                                self.logger.debug("检测到主控制器进入急停状态!检测AGV任务状态，取消下发的任务")
                                # self.sqlHd.update_table_eqp_data_status()
                                if self.AGVSendFileThreadStart:
                                    self.set_AGV_call_off_request()
                        else:
                            self.states.mainZmcStates.rs = False
                            if self.states.mainZmcIsRs:
                                self.states.mainZmcIsRs = False
                                newData = {
                                    "mainZmcRunning": 0
                                }
                                self.db.save_working_info_data(newData)
                                self.logger.debug("检测到收板主控制器急停状态去除!")
                                # self.sqlHd.update_table_eqp_data_status()

                    ret, val = self.mainZmc.is_running()
                    if ret == 0:
                        if val == 1:
                            self.states.mainZmcStates.run = True
                            if not self.states.mainZmcIsRun:
                                self.states.mainZmcIsRun = True
                                newData = {
                                    "mainZmcRunning": 1
                                }
                                self.db.save_working_info_data(newData)
                                self.logger.debug("检测到收板主控制器进入运行状态!")
                                # self.sqlHd.update_table_eqp_data_status()
                        else:
                            self.states.mainZmcStates.run = False
                            if self.states.mainZmcIsRun:
                                self.states.mainZmcIsRun = False
                                newData = {
                                    "mainZmcRunning": 0
                                }
                                self.db.save_working_info_data(newData)
                                self.logger.debug("检测到主控制器进入停止状态! 检测AGV任务状态，取消下发的任务")
                                # self.sqlHd.update_table_eqp_data_status()
                                if self.AGVSendFileThreadStart:
                                    self.set_AGV_call_off_request()
                else:
                    connectRes = self.mainZmc.reconnect_main_zmc()
                    if connectRes == "ok":
                        self.states.mainZmcStates.online = True
                        self.states.mainZmcStates.rs = False
                        self.states.mainZmcStates.run = False
                    else:
                        self.states.mainZmcStates.online = False
                        self.states.mainZmcStates.rs = False
                        self.states.mainZmcStates.run = False
                    newData = {
                        "mainZmcRunning": 0
                    }
                    self.db.save_working_info_data(newData)
                    # self.sqlHd.update_table_eqp_data_status()
                gevent.sleep(self.loopDuration)
            except Exception as e:
                errorInfo = "in main_zmc_listener(): error: {}".format(str(e))
                print(errorInfo)
                self.logger.debug(errorInfo)

    def cam_zmc_listener(self):
        """
        分流机控制器的监听线程类
        :return:
        """
        while settings.IS_MAIN_ALIVE:
            try:
                connectState = self.camZmc.check_connect()
                if connectState:
                    # val = [self.camZmc.get_modbus_bit(bitNum, 1)[1][0] for bitNum in range(500, 535)]
                    # alarmInfo = self.get_main_alarm_info_by_bit_val(val)
                    # self.states.mainAlarmInfo = alarmInfo
                    # self.states.mainAlarmInfoVisible = True if alarmInfo != "" else False

                    grateHidded = self.camZmc.get_grade_state()
                    self.states.grateHidded = grateHidded

                    doorAlarm = self.camZmc.get_door_state()
                    self.states.doorAlarm = doorAlarm

                    ret, val = self.camZmc.is_rs_stop()
                    if ret != 0:
                        if val == 1:
                            self.states.camZmcStates.rs = True
                            if not self.states.camZmcIsRs:
                                self.states.camZmcIsRs = True
                                self.logger.debug("检测到分流机主控制器进入急停状态!")
                        else:
                            self.states.camZmcStates.rs = False
                            if self.states.camZmcIsRs:
                                self.states.camZmcIsRs = False
                                self.logger.debug("检测到分流机主控制器急停状态去除!")

                    ret, val = self.camZmc.is_running()
                    if ret == 0:
                        if val == 1:
                            self.states.camZmcStates.run = True
                            if not self.states.camZmcIsRun:
                                self.states.camZmcIsRun = True
                                self.logger.debug("检测到分流机主控制器进入运行状态!")
                        else:
                            self.states.camZmcStates.run = False
                            if self.states.camZmcIsRun:
                                self.states.camZmcIsRun = False
                                self.logger.debug("检测到分流机主控制器进入停止状态!")
                else:
                    connectRes = self.camZmc.reconnect_main_zmc()
                    if connectRes == "ok":
                        self.states.camZmcStates.online = True
                        self.states.camZmcStates.rs = False
                        self.states.camZmcStates.run = False
                    else:
                        self.states.camZmcStates.online = False
                        self.states.camZmcStates.rs = False
                        self.states.camZmcStates.run = False
                gevent.sleep(self.loopDuration)
            except Exception as e:
                errorInfo = "in cam_zmc_listener(): error: {}".format(str(e))
                print(errorInfo)
                self.logger.debug(errorInfo)

    def get_main_alarm_info_by_bit_val(self, val):
        """
        根据底层的bit位信息,获取报警信息,如果没有报警信息,就返回空串,或者出错,也返回空串
        :param val:
        :return:
        """
        try:
            alarmVal = [500 + index for index, bitVal in enumerate(val) if bitVal != 0]
            # 获取报警信息的内容
            res, alarmData = self.db.get_main_alarm_info()
            if res != "ok":
                errorInfo = "in get_alarm_info_by_bit_val() error: get_main_alarm_info数据错误,数据库异常"
                print(errorInfo)
                self.logger.debug(errorInfo)
            else:
                infoDict = alarmData.get("mainAlarmInfo")
                alarmInfo = ""
                for alarmBit in alarmVal:
                    info = infoDict.get(str(alarmBit), "")
                    if info != "":
                        if alarmInfo != "":
                            alarmInfo = alarmInfo + ", " + info
                        else:
                            alarmInfo = info
                return alarmInfo
        except Exception as e:
            errorInfo = "in get_alarm_info_by_bit_val: error:{}".format(str(e))
            print(errorInfo)
            self.logger.debug(errorInfo)

    def camera_group_listener(self):
        """
        相机组的监听线程类
        :return:
        """
        cameraConnected = True
        camera2Connected = True
        while settings.IS_MAIN_ALIVE:
            camera1IsOnline = self.camera1.is_device_online()
            # camera2IsOnline = self.camera2.is_device_online()
            self.states.cameraGroupStates[0] = camera1IsOnline
            if not camera1IsOnline:
                ret = self.reconnect_camera1()
                if ret != 0:
                    if cameraConnected:
                        self.logger.debug(ret)
                    cameraConnected = False
                else:
                    camera1IsOnline = True
                    cameraConnected = True
                    self.logger.debug("相机1连接成功!")

            # if not camera2IsOnline:
            #     ret = self.reconnect_camera2()
            #     if ret != 0:
            #         if camera2Connected:
            #             self.logger.debug(ret)
            #         camera2Connected = False
            #         self.camZmc.set_cam2_screen_start(0)
            #     else:
            #         camera2IsOnline = True
            #         camera2Connected = True
            #         self.logger.debug("相机2连接成功!")
            #         self.camZmc.set_cam2_screen_start(1)
            self.states.cameraGroupStates[0] = camera1IsOnline
            gevent.sleep(self.loopDuration)

    def reconnect_camera1(self):
        try:
            ret = self.camera1.re_connect_area_camera()
            if ret != 0:
                self.camera1.errorMsg = "相机连接失败,原因:{}".format(ret)
                # self.sqlHd.update_table_qp_data_alarm("相机1通讯异常", 1)
                return self.camera1.errorMsg
            else:
                return 0
        except Exception as e:
            print("in reconnect_camera() error : {}".format(str(e)))
            return "相机连接失败1,失败原因:{}".format(str(e))

    def reconnect_camera2(self):
        try:
            ret = self.camera2.re_connect_area_camera()
            if ret != 0:
                self.camera2.errorMsg = "相机2连接失败,原因:{}".format(ret)
                # self.sqlHd.update_table_qp_data_alarm("相机2通讯异常", 1)
                return self.camera2.errorMsg
            else:
                return 0
        except Exception as e:
            print("in reconnect_camera2() error : {}".format(str(e)))
            return "相机连接失败2,失败原因:{}".format(str(e))

    def Handler(self):
        while settings.IS_MAIN_ALIVE:
            # 等待新的客户端连接
            self.cameraGroupStates = False
            self.states.cameraGroupStates[1] = self.cameraGroupStates
            self.states.client_socket, client_address = self.socketService.accept()
            print('服务器正在运行，等待客户端连接...')
            try:
                print('客户端已连接:', client_address)
                self.cameraGroupStates = True
                self.states.cameraGroupStates[1] = self.cameraGroupStates
                # if
                while True:
                    # 接收客户端发送的数据
                    data = self.states.client_socket.recv(1024)
                    if data:
                        # 处理接收到的数据
                        print('接收到来自客户端的数据:{}'.format(data))
                        self.logger.debug(data)
                        gevent.sleep(1)
                    else:
                        # 客户端断开连接
                        print('客户端已断开连接:', client_address)
                        self.cameraGroupStates = False
                        self.states.cameraGroupStates[1] = self.cameraGroupStates
                        break
            except Exception as e:
                print(e)
                gevent.sleep(1)
                continue
            finally:
                # 关闭客户端连接
                self.states.client_socket.close()
                self.states.client_socket = None
                break

    def manager(self):
        """
        线程管理类
        :return:
        """
        self.updateStatesFlag = False
        while settings.IS_MAIN_ALIVE:
            # 先将已就那个存放的叠板厚度的信息获取一下，然后更新到数据库中
            # 获取叠板厚度的信息
            boardThicknessTable = self.db.get_board_thickness()[1]
            self.states.boardThicknessMax = [boardThicknessTable]
            # 实时更新设备状态
            self.send_device_state_to_ui()
            try:

                if not self.mainZmcListenerThread.is_alive():
                    self.mainZmcListenerThread = threading.Thread(target=self.main_zmc_listener, name="mainZmcListenerThread")
                    self.mainZmcListenerThread.setDaemon(True)
                    self.mainZmcListenerThread.start()

                if not self.camZmcListenerThread.is_alive():
                    self.camZmcListenerThread = threading.Thread(target=self.cam_zmc_listener, name="camZmcListenerThread")
                    self.camZmcListenerThread.setDaemon(True)
                    self.camZmcListenerThread.start()

                if not self.cameraGroupListenerThread.is_alive():
                    self.cameraGroupListenerThread = threading.Thread(target=self.camera_group_listener, name="maineraGroupListenerThread")
                    self.cameraGroupListenerThread.setDaemon(True)
                    self.cameraGroupListenerThread.start()

                if not self.AGVCommunicateListenerThread.is_alive():
                    self.AGVCommunicateListenerThread = threading.Thread(target=self.AGV_communicate_listener, name="AGVCommunicateListenerThread")
                    self.AGVCommunicateListenerThread.setDaemon(True)
                    self.AGVCommunicateListenerThread.start()

                if not self.handlerThread.is_alive():
                    self.handlerThread = threading.Thread(target=self.Handler, name="handlerThread")
                    self.handlerThread.setDaemon(True)
                    self.handlerThread.start()

                if not self.updateStatesFlag:
                    loginSuccess = self.db.get_login_state()
                    if loginSuccess:
                        gevent.sleep(0.3)
                        self.web_show_data_initial()
                        self.db.update_login_state(False)
                        self.updateStatesFlag = True
                    else:
                        msgVal = {
                            "usernames": self.db.get_usernames()[1]
                        }
                        send_login_usernames_to_ui(msgVal)
            except Exception as e:
                errorInfo = "in manager() error: {}".format(str(e))
                print(errorInfo)
                self.logger.debug(errorInfo)
                gevent.sleep(1)

            gevent.sleep(1)

    def web_show_data_initial(self):
        """
        前端界面的一些显示数据的初始化
        :return:
        """
        orderUsedKey = self.db.get_working_used_key()
        msg = {
            "val": orderUsedKey
        }
        # send_settings_state_to_ui()
        send_order_state_to_ui(msg)  # 更新工单的信息
        # 更新workingInfo的数据
        # send_working_info_state_to_ui()

    def AGV_laying_off(self, bitStart):
        if bitStart[0] == 1:
            self.mainZmc.set_modbus_bit(28, 0)
            return ""
        elif bitStart[1] == 1:
            self.mainZmc.set_modbus_bit(29, 0)
            return ""
        elif bitStart[2] == 1:
            return "20000001"
        elif bitStart[3] == 1:
            return "20000002"

    def AGV_communicate_listener(self):
        self.AGVSendFileThreadStart = False
        info = "AGV通讯线程开启，进入监听状态！"
        self.logger.debug(info)
        print(info)
        self.AGVSendFileThreadStart = False
        self.taskStatus = False
        while settings.IS_MAIN_ALIVE:
            try:
                if self.mainZmc.get_modbus_bit(70, 1) == 0:
                    gevent.sleep(2)
                    continue
                if not self.AGVSendFileThreadStart:
                    callOutAGVReclaimer = self.mainZmc.get_call_out_AGV_start()
                    QRCode = self.AGV_laying_off(callOutAGVReclaimer)
                    if QRCode == "20000001" or QRCode == "20000002":
                        gevent.sleep(0.5)
                        self.QRCode = QRCode
                        self.logger.debug(self.QRCode)
                        self.AGVSendFileThreadStart = True
                        gevent.sleep(0.5)

                if self.AGVSendFileThreadStart:
                    res, info = self.AGV_communiccate_start(self.QRCode)
                    if res == "ok":
                        if self.QRCode == "20000001":
                            bitValue = 61
                        elif self.QRCode == "20000002":
                            bitValue = 63
                        self.taskStatus = False
                        self.mainZmc.set_modbus_bit(bitValue, 1)
                        self.AGVSendFileThreadStart = False
                        self.logger.debug("{},托盘{}上升".format(info, self.QRCode))
                        gevent.sleep(0.5)
                    else:
                        self.taskStatus = False
                        self.logger.debug(info)
                        self.AGVSendFileThreadStart = False
                        gevent.sleep(0.5)
                else:
                    gevent.sleep(3)
                    continue
            except Exception as e:
                errorInfo = "in AGV_laying_off_listener(): error: {}".format(str(e))
                print(errorInfo)
                self.logger.debug(errorInfo)
                # self.sqlHd.update_table_qp_data_alarm("AGV通讯异常", 1)
                self.AGVSendFileThreadStart = False
                self.taskStatus = False
                gevent.sleep(3)
                continue

    def task_status_tail_after(self, orderId):
        count = 5
        self.infoStartAGV = ""
        while self.taskStatus:
            response = get_task_status("HD{}".format(orderId))
            response = json.loads(str(response, 'utf8'))
            if response.get('code') == 1000:
                if response.get("data").get("status") == 8:
                    if self.infoStartAGV != "收板机下料任务完成！":
                        print("收板机下料任务完成！")
                        self.infoStartAGV = "收板机下料任务完成！"
                        self.taskStatus = False
                        gevent.sleep(0.1)
                        break
                elif response.get("data").get("status") == 1:
                    if self.infoStartAGV != "收板机下料任务未发送！":
                        print("收板机下料任务未发送！")
                        self.infoStartAGV = "收板机下料任务未发送！"
                        self.logger.debug(self.infoStartAGV)
                        gevent.sleep(5)
                        continue
                    else:
                        gevent.sleep(5)
                        continue
                elif response.get("data").get("status") == 4:
                    if self.infoStartAGV != "收板机下料任务正在发送！":
                        print("收板机下料任务正在发送！")
                        self.infoStartAGV = "收板机下料任务正在发送！"
                        self.logger.debug(self.infoStartAGV)
                        gevent.sleep(5)
                        continue
                    else:
                        gevent.sleep(5)
                        continue
                elif response.get("data").get("status") == 9:
                    if self.infoStartAGV != "收板机下料任务已下发！":
                        print("收板机下料任务已下发！")
                        self.infoStartAGV = "收板机下料任务已下发！"
                        self.logger.debug(self.infoStartAGV)
                        gevent.sleep(5)
                        continue
                    else:
                        gevent.sleep(5)
                        continue
                elif response.get("data").get("status") == 6:
                    if self.infoStartAGV != "收板机下料任务运行中！":
                        print("收板机下料任务运行中！")
                        self.infoStartAGV = "收板机下料任务运行中！"
                        self.logger.debug(self.infoStartAGV)
                        gevent.sleep(5)
                        continue
                    else:
                        gevent.sleep(5)
                        continue
                elif response.get("data").get("status") == 7:
                    if self.infoStartAGV != "收板机下料任务执行失败！":
                        print("收板机下料任务执行失败！")
                        self.infoStartAGV = "收板机下料任务执行失败！"
                        self.logger.debug(self.infoStartAGV)
                        gevent.sleep(5)
                        continue
                    else:
                        self.taskStatus = False
                        gevent.sleep(0.1)
                        break
                elif response.get("data").get("status") == 5:
                    if self.infoStartAGV != "收板机下料任务发送失败！":
                        print("收板机下料任务发送失败！")
                        self.infoStartAGV = "收板机下料任务发送失败！"
                        self.logger.debug(self.infoStartAGV)
                        gevent.sleep(5)
                        continue
                    else:
                        self.taskStatus = False
                        gevent.sleep(0.1)
                        break
                elif response.get("data").get("status") == 3:
                    if self.infoStartAGV != "收板机下料任务已取消！":
                        print("收板机下料任务已取消！")
                        self.infoStartAGV = "收板机下料任务已取消！"
                        self.logger.debug(self.infoStartAGV)
                        gevent.sleep(5)
                        continue
                    else:
                        self.taskStatus = False
                        gevent.sleep(0.1)
                        break
                elif response.get("data").get("status") == 10:
                    if self.infoStartAGV != "收板机下料任务等待确认！":
                        print("收板机下料任务等待确认！")
                        self.infoStartAGV = "收板机下料任务等待确认！"
                        self.logger.debug(self.infoStartAGV)
                        gevent.sleep(5)
                        continue
                    else:
                        gevent.sleep(5)
                        continue
                else:
                    if count > 0:
                        print("获取的任务状态异常！, 重新获取")
                        self.infoStartAGV = "获取的任务状态异常！, 重新获取"
                        self.logger.debug("获取的任务状态异常！, 重新获取")
                        count = -1
                        gevent.sleep(5)
                        continue
                    else:
                        self.infoStartAGV = ("获取的任务状态异常！, 多次获取失败！退出循环！")
                        self.taskStatus = False
                        gevent.sleep(0.1)
                        break
        if self.infoStartAGV != "收板机下料任务完成！":
            return False, self.infoStartAGV
        else:
            return "ok", self.infoStartAGV

    def AGV_communiccate_start(self, id):
        self.timestamp = int(time.time())
        responseCall = call_out_AGV_Reclaimer_01(self.timestamp, id)
        responseCall = json.loads(str(responseCall, 'utf8'))
        if responseCall.get('code') == 1000:
            self.infoStartAGV = "收板机下料任务下发成功！下发时间戳{}, 下发的点位{}".format(self.timestamp, id)
            if id == "20000001":
                self.mainZmc.set_modbus_bit(34, 0)
                self.logger.debug("bit 34=0")
            elif id == "20000002":
                self.mainZmc.set_modbus_bit(35, 0)
                self.logger.debug("bit 35=0")
            self.taskStatus = True
            gevent.sleep(0.1)
            self.logger.debug(self.infoStartAGV)
            res, info = self.task_status_tail_after(self.timestamp)
            return res, info
        else:
            self.infoStartAGV = "呼叫AGV失败！{}, 请检查通讯是否正常！".format(id)
            return "false", "呼叫AGV失败！"

    def set_AGV_call_off_request(self):
        responseCall = set_call_off_request(self.timestamp)
        responseCall = json.loads(str(responseCall, 'utf8'))
        if responseCall.get('code') == 1000:
            info = "下料模式由AGV模式变换为手动模式,已下发的AGV下料任务编号 HD{} 已取消！".format(self.timestamp)
            self.infoStartAGV = info
            self.AGVSendFileThreadStart = False
            self.logger.debug(info)
        else:
            info = "下料模式由AGV模式变换为手动模式,已下发的AGV下料任务编号 HD{} 取消失败！".format(self.timestamp)
            self.infoStartAGV = info
            self.AGVSendFileThreadStart = False
            self.logger.debug(info)

    def send_device_state_to_ui(self):
        """
        将device的状态信息发送给前端,就是状态类监控到的设备信息
        :return:
        """
        msgType = "deviceStates"
        msg = self.states.pack_state_to_dict()
        send_msg_to_ui(msgType, msg)
